
var chooseSceneNo = 0;
var eKnowSceneList = [];
//关联场景弹框开启
function chooseSceneOpen(){
    $.ajax({
        url : '/api/inter/eKnowChatSetController/getEKnowSceneList',
        data : {},
        type : 'POST',
        async : false,
        success : function(result) {
            if(result.code=='SUCCESS'){
                var sceneId = $('#sceneId').val();//当前场景id
                chooseSceneNo = sceneId;
                eKnowSceneList = result.eKnowSceneList;
                var htmlStr = '<div class="layui-bg-gray" style="padding: 16px;max-height:calc(100vh - 90px);overflow: auto;"><div class="layui-row layui-col-space15">';
                if(eKnowSceneList!=null && eKnowSceneList.length>0){
                    for(var i=0;i<eKnowSceneList.length;i++){
                        var isChooseed = false;
                        var id = eKnowSceneList[i].id;
                        if(chooseSceneNo!=null && chooseSceneNo!=0){
                            if(chooseSceneNo==id)isChooseed=true;
                        }
                        htmlStr+='<div class="layui-col-md6" style="cursor: pointer;" onclick="chooseScene(\''+id+'\');">'+
                            '<div id="chooseView'+id+'" class="layui-card choose-view-none '+(isChooseed?'choose-view':'')+'">'+
                            '<div class="layui-card-header"  style="white-space: nowrap;overflow: hidden;text-overflow: ellipsis;" title="'+eKnowSceneList[i].sceneName+'">' +eKnowSceneList[i].sceneName+
                            '<div style="float: right;" id="checkbox'+id+'" '+(isChooseed?'':'hidden')+'><i class="layui-icon layui-icon-ok" style="color: #4BB2FF;font-weight: bold;"></i></div>'+
                            '</div>'+
                            '<div class="layui-card-body" style="height: 100px;"><span class="list-span" title="'+eKnowSceneList[i].sceneDescribe+'">' +eKnowSceneList[i].sceneDescribe+'</span></div></div></div>';
                    }
                }
                htmlStr+='</div>'+
                    '<div class="bottom-view-open">'+
                    '<div class="layui-btn-container add-btn-view-open">'+
                    '<button type="button" class="layui-btn layui-bg-blue add-btn-open" onclick="yesChooseScene();">确定</button> '+
                    '</div>'+
                    '</div>';
                layer.open({
                    title:'选择场景',
                    type: 1,
                    offset: 'r',
                    anim: 'slideLeft', // 从右往左
                    area: ['500px', '100%'],
                    shade: 0.5,
                    shadeClose: true,
                    closeBtn:0,
                    id: 'ID-demo-layer-direction-r',
                    content:htmlStr
                })
            }else{
                layer.msg('不好意思，系统出现问题了，请稍后重试！', {icon: 2});
            }
        }
    });
}

//弹框选择场景样式
function chooseScene(id){
    chooseSceneNo = id;
    var oldId = $('#sceneId').val();
    if(oldId!=id){
        //旧的取消
        $('#chooseView'+oldId).removeClass('choose-view');
        $('#checkbox'+oldId).hide();
        //添加新选择
        $('#chooseView'+id).addClass('choose-view');
        $('#checkbox'+id).show();
        $('#sceneId').val(id);

    }else {
        //chooseListNo.push({id:id,name:name});
        //$('#chooseView'+id).addClass('choose-view');
        //$('#checkbox'+id).show();
    }
}

//确认
function yesChooseScene() {
    layer.load(2);
    $('#sceneId').val(chooseSceneNo);
    resetSceneSet();
}

//重新设置场景信息
function resetSceneSet(){
    var sceneId = $('#sceneId').val();

    //获取场景信息
    $.ajax({
        url: '/api/inter/eKnowChatSetController/getEKnowSceneSet',
        data: {
            'sceneId':sceneId
        },
        type: 'POST',
        async: true,
        success: function (result) {
            console.log('result',result);
            $('#box').show();
            var eKnowScene = result.eKnowScene;
            var modelList = result.modelList;
            var promptKeyList = result.promptKeyList;
            var knowledgeBaseList = result.knowledgeBaseList;
            var userSetAiName = result.userSetAiName;
            eKnowSceneInfo = eKnowScene;
            //头部信息配置
            $('#sceneMsgNo').hide();
            $('#sceneMsg').show();
            $('#sceneMsg').text('配置由'+eKnowScene.userName+'更新于'+eKnowScene.updateTime);
            $('#senceNameSet').text('当前场景：'+eKnowScene.sceneName);
            $('#saveBtn').show();
            //重新设置左边配置信息
            reSetLeftSet(eKnowScene,modelList,promptKeyList,knowledgeBaseList);
            //配置中间聊天页面信息
            setChatView(eKnowScene,userSetAiName,modelList);
            //动画
            var animStr = 'layui-anim-upbit';
            var aiTalkHtml = '<div class="layui-row ai-chat">\n' +
                '            <div class="layui-col-xs1"><div class="grid-demo grid-demo-bg1 layui-anim '+animStr+'">' +headTypeHtml+ '</div></div>\n' +
                '            <div class="layui-col-xs10"><div class="ai-content layui-anim '+animStr+'"><span>'+$('#prologue').val()+'</span></div></div>\n' +
                '            <div class="layui-col-xs1" style="width: 100%;"></div>\n' +
                '        </div>';
            $('#chat_view').html(aiTalkHtml);
            $('#noMoreRecordTxt').show();
            $('#moreRecordBtn').hide();
            $('#moreRecordLoading').hide();
            chooseAiModelList = [];//选择的ai模型信息
            for(var i=0;i<modelList.length;i++){
                chooseAiModelList.push({id:modelList[i].id,modelOwnName:modelList[i].modelOwnName});
            }
            chooseLedgeBaseList = [];//选择的知识库配置信息
            for(var i=0;i<knowledgeBaseList.length;i++){
                chooseLedgeBaseList.push({id:knowledgeBaseList[i].id,name:knowledgeBaseList[i].knowledgeBaseName});
            }

            layer.closeAll();
        },
        error: function () {}
    });

}
//重新设置左边配置信息
function reSetLeftSet(eKnowScene,modelList,promptKeyList,knowledgeBaseList) {
    $('#modelDefaultNameSet').val(eKnowScene.modelDefaultName);//默认角色名
    //自定义角色名开关
    if(eKnowScene.modelRoleIsOpen=='1'){//开启
        $('#modelRoleIsOpenSet').attr('checked',true);
        $('#modelRoleIsOpenSetView').html('<input type="checkbox" name="modelRoleIsOpenSet" id="modelRoleIsOpenSet" lay-skin="switch" lay-filter="switchModelRoleIsOpenSet" title="开|关" checked>');
    }else {//关闭
        $('#modelRoleIsOpenSet').attr('checked',false);
        $('#modelRoleIsOpenSetView').html('<input type="checkbox" name="modelRoleIsOpenSet" id="modelRoleIsOpenSet" lay-skin="switch" lay-filter="switchModelRoleIsOpenSet" title="开|关">');
    }
    $('#aiSystemSet').val(eKnowScene.aiSystem);//ai人设
    $('#prologueSet').val(eKnowScene.prologue);//开场白设置
    $('#sorryTxtSet').val(eKnowScene.sorryTxt);//模型无法回答时的提示语
    //所选AI模型
    var htmlStrModel = '';
    for(var i=0;i<modelList.length;i++){
        htmlStrModel+='<button type="button" class="layui-btn layui-btn-xs" onclick="delChooseModel(\''+modelList[i].id+'\')">'+modelList[i].modelOwnName+' <i class="layui-icon layui-icon-close layui-font-12"></i></button>';
    }
    $('#chooseModelBtn').html(htmlStrModel);
    //所选知识库
    var htmlStrLedge = '';
    for(var i=0;i<knowledgeBaseList.length;i++){
        htmlStrLedge+='<button type="button" class="layui-btn layui-btn-xs" onclick="delChooseLedge(\''+knowledgeBaseList[i].id+'\')">'+knowledgeBaseList[i].knowledgeBaseName+' <i class="layui-icon layui-icon-close layui-font-12"></i></button>';
    }

    $('#chooseLedgeBtn').html(htmlStrLedge);
    //向量数据库调用个数、置信度
    sliderSet(eKnowScene.embeddingBackCount,eKnowScene.embeddingBackSource);
    //提示词
    for(var i=0;i<promptKeyList.length;i++){
        if(promptKeyList[i].keyId=='3' && promptKeyList[i].keyValue!=null){//有知识库问答提示词
            $('#withPromptSet').val(promptKeyList[i].keyValue);
        }
        if(promptKeyList[i].keyId=='4' && promptKeyList[i].keyValue!=null){//无知识库问答提示词
            $('#noPromptSet').val(promptKeyList[i].keyValue);
        }
    }
    //是否限制用户每天对话次数
    if(eKnowScene.isLimitTimes=='1'){//开启
        $('#isLimitTimesSet').attr('checked',true);
        $('#isLimitTimesSetView').html('<input type="checkbox" name="isLimitTimesSet" id="isLimitTimesSet" lay-skin="switch" lay-filter="switchIsLimitTimesSet" title="开|关" checked>');
        $('#userChatTimesView').show();
        $('#userChatTimesSet').val(eKnowScene.userChatTimes);
    }else {//关闭
        $('#isLimitTimesSet').attr('checked',false);
        $('#isLimitTimesSetView').html('<input type="checkbox" name="isLimitTimesSet" id="isLimitTimesSet" lay-skin="switch" lay-filter="switchIsLimitTimesSet" title="开|关">');
        $('#userChatTimesView').hide();
    }
    //提问字数限制
    $('#inputMaxSet').val(eKnowScene.inputMax);
    //开启聊天是否默认新会话
    if(eKnowScene.openIsNewChat=='1'){//开启
        $('#openIsNewChatSet').attr('checked',true);
        $('#openIsNewChatSetView').html('<input type="checkbox" name="openIsNewChatSet" id="openIsNewChatSet" lay-skin="switch" lay-filter="switchOpenIsNewChatSet" title="开|关" checked>');
    }else {//关闭
        $('#openIsNewChatSet').attr('checked',false);
        $('#openIsNewChatSetView').html('<input type="checkbox" name="openIsNewChatSet" id="openIsNewChatSet" lay-skin="switch" lay-filter="switchOpenIsNewChatSet" title="开|关">');
    }
    //是否显示选择提示词模版
    if(eKnowScene.questionTemplateIsOpen=='1'){//开启
        $('#questionTemplateIsOpenSet').attr('checked',true);
        $('#questionTemplateIsOpenSetView').html('<input type="checkbox" name="questionTemplateIsOpenSet" id="questionTemplateIsOpenSet" lay-skin="switch" lay-filter="switchQuestionTemplateIsOpenSet" title="开|关" checked>');
        $('#questionTemplateView').show();
        $('#questionTemplateTxtSet').val(eKnowScene.questionTemplateTxt);
    }else {//关闭
        $('#questionTemplateIsOpenSet').attr('checked',false);
        $('#questionTemplateIsOpenSetView').html('<input type="checkbox" name="questionTemplateIsOpenSet" id="questionTemplateIsOpenSet" lay-skin="switch" lay-filter="switchQuestionTemplateIsOpenSet" title="开|关">');
        $('#questionTemplateView').hide();
    }
    layui.form.render();
}


//应用配置
function saveSceneSet() {
    layer.confirm('确定应用该场景的配置?', {icon: 3}, function () {
        //点击确定的回调
        layer.load(2);
        yesSaveSceneSet();
    }, function () {});//点击取消的回调
}

//确定应用配置
function yesSaveSceneSet() {
    //参数验证
    if(!checkSaveSet()){
        return;
    }
    var ledgeBaseList = '';
    for(var i=0;i<chooseLedgeBaseList.length;i++){
        if(ledgeBaseList==''){
            ledgeBaseList = chooseLedgeBaseList[i].id;
        }else {
            ledgeBaseList += ','+chooseLedgeBaseList[i].id;
        }
    }
    var modelIdList = '';
    for(var i=0;i<chooseAiModelList.length;i++){
        if(modelIdList==''){
            modelIdList = chooseAiModelList[i].id;
        }else {
            modelIdList += ','+chooseAiModelList[i].id;
        }
    }

    //更新场景信息
    $.ajax({
        url: '/api/inter/eKnowChatSetController/updateScene',
        data: {
            'sceneId':eKnowSceneInfo.id,
            'modelDefaultName':$('#modelDefaultNameSet').val(),
            'modelRoleIsOpen':eKnowSceneInfo.modelRoleIsOpen,
            'aiSystem':$('#aiSystemSet').val(),
            'prologue':$('#prologueSet').val(),
            'sorryTxt':$('#sorryTxtSet').val(),
            'embeddingBackCount':eKnowSceneInfo.embeddingBackCount,
            'embeddingBackSource':eKnowSceneInfo.embeddingBackSource,
            'isLimitTimes':eKnowSceneInfo.isLimitTimes,
            'userChatTimes':$('#userChatTimesSet').val(),
            'inputMax':$('#inputMaxSet').val(),
            'openIsNewChat':eKnowSceneInfo.openIsNewChat,
            'noPromptSet':returnValueIsNull($('#noPromptSet').val()),
            'withPromptSet':returnValueIsNull($('#withPromptSet').val()),
            'modelIdList':modelIdList,
            'ledgeBaseList':ledgeBaseList,
            'questionTemplateIsOpen':eKnowSceneInfo.questionTemplateIsOpen,
            'questionTemplateTxt':eKnowSceneInfo.questionTemplateTxt,
        },
        type: 'POST',
        async: true,
        success: function (result) {
            layer.closeAll();
            if(result.code=='SUCCESS'){
                layer.msg("操作成功", {icon: 1});
                $('#sceneMsg').text('配置由'+result.userName+'更新于'+result.updateTime);
            }else{//失败
                layer.msg('不好意思，系统出现问题了，请稍后重试！', {icon: 2});
            }

        },
        error: function () {
            layer.closeAll();
            layer.msg('不好意思，系统出现问题了，请稍后重试！', {icon: 2});
        }
    });

}

